package com.taocyb.framework.security.simple;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.taocyb.commons.uc.entity.User;
import com.taocyb.commons.uc.service.UserService;
import com.taocyb.framework.utils.SecurityUtils;
import com.taocyb.framework.utils.Servlets;

/**
 * 登录授权拦截器 
 */
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	private String loginUrl = "/";
	
	@Autowired
	private UserService userService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if(!(handler instanceof HandlerMethod)){
			return super.preHandle(request, response, handler);
		}
		
		HandlerMethod method = (HandlerMethod) handler;
		Authentication authentication = method.getMethodAnnotation(Authentication.class);
		
		if(null == authentication){
			return super.preHandle(request, response, handler);
		}
		
		boolean isLogin = false;
		Cookie cookie = Servlets.getCookie(request, "_uid");
		if(cookie != null){
			String cookieValue = new String(Base64.decodeBase64(cookie.getValue()));
			String[] values = cookieValue.split(":");
			if(values.length == 3){
				String cookieLoginName = values[0];
				long cookieValidTime = Long.parseLong(values[1]);
				String cookieMd5Value = values[2];
				
				if(cookieValidTime > System.currentTimeMillis()){
					User user = userService.findUserByLoginName(cookieLoginName);
					String md5Value = SecurityUtils.encryptCookieValueMd5(user.getLoginName(), user.getPassword());
					if(md5Value.equals(cookieMd5Value)){
						isLogin = true;
					}else{
						logger.debug("非法参数，清除cookie");
					}
				}else{
					logger.debug("登录时间失效, 清除cookie");
				}
			}
		}
		
		if(!isLogin){
			//json请求处理
			if(MediaType.APPLICATION_JSON_VALUE.equals(request.getContentType())){
				
			}else{	//普通请求
				 response.sendRedirect(request.getContextPath() + loginUrl);  
			}
			
			return false;
		}
		
		return super.preHandle(request, response, handler);
	}

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}
}
